//
//  RootViewController.m
//  MUBATE
//
//  Created by sunbin on 2017/2/16.
//  Copyright © 2017年 Quanli. All rights reserved.
//

#import "RootViewController.h"
#import "GetUserInfo.h"


#import "RecentRecordCell.h"

#import "RequestManage.h"
#import "RecentRecordModel.h"


#import "FinancialReport.h"
#import "ConcentricModel.h"
#import "RecordDetails.h"

#import "RecordSlide.h"


#import "NewMessage.h"

#import "Masonry.h"
#import "YHomeItemRoundCell.h"

#import "CorporateCenter.h"

#define leftWidth kscaleHeight(250)
static NSString * YXHomeItemRound = @"HomeItemRound_Identifier";

static NSString * RecentRecordCellIdentifier = @"RecentRecordCellIdentifier";


@interface RootViewController ()<UITableViewDataSource,UITableViewDelegate  ,LeftMenuDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *chartCollectionView;
@property (weak, nonatomic) IBOutlet UITableView *recentRecoderTableView;
@property (nonatomic, strong) NSMutableArray *recoderListArr;
@property (nonatomic, strong) NSMutableDictionary *concentricData;

@end

@implementation RootViewController
{
    NSArray *apiAry ,*paramsAry ,*modelAry;
}
// lazy加载 _recoderListArr _concentricData
- (NSMutableArray *)recoderListArr
{
    if (!_recoderListArr) {
        _recoderListArr = [NSMutableArray array];
    }
    return _recoderListArr;
}

- (NSMutableDictionary *)concentricData
{
    if (!_concentricData) {
        _concentricData = [NSMutableDictionary dictionary];
    }
    return _concentricData;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    self.jHUDRect = _recentRecoderTableView.frame;

    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [self getInfor];

    [self loadData];

    [self initView];
}



- (void)initView{
    [self theChart];
    // 注册xib cell
    [self registerNib];
    // 抽屉菜单 左侧视图  leftBarButton左侧按钮
    [self menuView];[self leftBarButton];
    
    // 设置通知
    [self notification];


}
// 注册cell
- (void)registerNib{
    [self.recentRecoderTableView registerNib:[UINib nibWithNibName:@"RecentRecordCell" bundle:nil] forCellReuseIdentifier:RecentRecordCellIdentifier];
    [self.chartCollectionView registerNib:[UINib nibWithNibName:@"YHomeItemRoundCell" bundle:nil] forCellWithReuseIdentifier:YXHomeItemRound];
}
- (void)notification{
    // 激光监听连接状态 长连接
    [self jpush];

    // 监听网络
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStatus) name:NETWORKSTATUS object:nil];
    

    // 数据清理

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataClear) name:CLEARCACHE object:nil];

}

// 重新启动网络连接 刷新数据
- (void)networkStatus{
    
    [self loadData];[self registerNib];
}

// 数据清空 网络延迟
- (void)dataClear{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:CLEANRECORD object:nil];

    [self performSelector:@selector(clearData) withObject:nil afterDelay:2.0];
}

-(void)clearData {
    [self.recoderListArr  removeAllObjects];
    [self.concentricData  removeAllObjects];

    if ([ZL_NetworkHelper currentNetworkStatus]) {
        [self loadData];

    }else{
        [self.recentRecoderTableView reloadData];
        WEAKSELF
        [weakSelf loadingFailure:@"无数据" refreshTitle:@"Refresh ?" customImage:@"nullData" indicatorViewSize:CGSizeMake(50, 50) showAtView:weakSelf.recentRecoderTableView];

    }


    // 清理数据后无数据显示无网络
}

#pragma make -YMenuView 左侧滑动视图
- (void)menuView
{
    // 设置 
    _left = [[YLeftMenu alloc]initWithFrame:CGRectMake(0, 0, leftWidth, SCREEN_HEIGHT)];
    _left.backgroundColor = [UIColor leftViewBackGroundColor];
    _left.customDelegate = self;
    
    YMenuView *menu = [YMenuView MenuViewWithDependencyView:self.view MenuView:_left isShowCoverView:YES];
    self.menu = menu;
}

#pragma make -LeftMenuDelegate
-(void)LeftMenuViewClick:(NSInteger)tag{
    [self.menu hidenWithAnimation];

    [self.navigationController pushViewController:@[
                                                    kVCFromSb(@"CorporateCenterID", @"CorporateCenter") ,
                                                    kVCFromSb(@"UserQrCodeID", @"UserQrCode"),
                                                    kVCFromSb(@"SetID",@"Set")][tag]
                                         animated:NO];
}

// 抽屉效果展示
- (void)leftBarButton{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:Icon(@"navigationbar-sidebar") style:UIBarButtonItemStylePlain target:self action:@selector(leftNavAction)];
}


// 导航左侧按钮点击事件
- (void)leftNavAction{
    [self.menu show];
}

- (void)theChart{
    _chartCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _chartCollectionView.backgroundColor = [UIColor clearColor];
    _chartCollectionView.pagingEnabled = YES;
}


// 获取用户资料
- (void)getInfor{
    [GetUserInfo userInfor];[self.recentRecoderTableView reloadData];
}



- (void)loadData{
    
    apiAry    = @[STOREMONEYLOG ,HOMEDATA];
    paramsAry = @[@{@"uid":@([YConfig getOwnID]) ,@"sign":SIGN ,@"start":@(0) ,@"count":@(10)},
                  @{@"uid":@([YConfig getOwnID]) ,@"sign":SIGN}];
    modelAry  = @[@"RecentRecordModel" ,@"ConcentricModel"];
    
    WEAKSELF;
    [RequestManage requestApi:apiAry params:paramsAry model:modelAry responseCache:^(BOOL isHaveCash, NSInteger index ,NSDictionary *cashDic ,NSMutableArray *cashAry) {
        // 只有在无网络 或请求失败获取缓存
        NSLog(@"responseCache = %ld %@ %@",(long)index ,cashDic ,cashAry);

    } refreshHeadler:^(int index) {
        
    } success:^(NSDictionary *succesSults, NSMutableArray *dataAry, NSString *successRequestmsg, NSInteger index) {
        NSLog(@"success=%@ ,%@ ,%@ ,%ld" ,succesSults ,dataAry ,successRequestmsg ,index);
        // 获取成功
        [weakSelf getData:succesSults modelData:dataAry index:index];
    } failure:^(NSDictionary * failedSults ,NSMutableArray *arySults, responseState resMake, NSString* RequestError , NSInteger index) {
        // 获取失败
        NSLog(@"failedSults=%@ ,%ld ,%@ ,%ld" ,failedSults ,(long)resMake ,RequestError ,index);
        NSLog(@"%@",arySults);
        //获取缓存数据 走缓存数据
        //获取网络数据 为保障arySults不为0 可做判断
        [weakSelf getData:failedSults modelData:arySults index:index];

    } showHub:^(bool isShowHub ,NSInteger index) {
        NSLog(@"showHub==%d ,%ld" ,isShowHub ,(long)index);
        // 显示jhud
        if (index == 0) {
            if (isShowHub) {
                [weakSelf loadingFailure:@"无数据" refreshTitle:@"Refresh ?" customImage:@"nullData" indicatorViewSize:CGSizeMake(50, 50) showAtView:weakSelf.recentRecoderTableView]; }
            
        }
    }];
}

- (void)getData:(NSDictionary *)dic modelData:(NSMutableArray *)modelData index:(NSInteger)index{
    WEAKSELF;
    switch (index) {
        case 0:
        {
            [weakSelf jhudHide:weakSelf.recentRecoderTableView];
            weakSelf.recoderListArr = modelData;
            [weakSelf.recentRecoderTableView reloadData];
        }
            break;
        case 1:
        {
            weakSelf.concentricData = [[NSMutableDictionary alloc] initWithDictionary:dic];
        
        }
            break;
            
        default:
            break;}
}



#pragma make -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.recoderListArr.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RecentRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:RecentRecordCellIdentifier forIndexPath:indexPath];
    RecentRecordModel *model = self.recoderListArr[indexPath.row];
    cell.model = model;
    
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    RecentRecordModel *model = self.recoderListArr[indexPath.row];
    RecordDetails *recordDetails = [[RecordDetails alloc] initWithNibName:@"RecordDetails" bundle:nil];
    recordDetails.model = model;
    recordDetails.ty = [model.type integerValue] - 1;
    recordDetails.dataTy = modelTy;

    [self.navigationController pushViewController:recordDetails animated:NO];
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kscaleHeight(50.f);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kscaleHeight(0.1f);
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    { [cell setSeparatorInset:UIEdgeInsetsMake(0, 15, 0, 15)];}
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    { [cell setLayoutMargins:UIEdgeInsetsMake(0, 15, 0, 15)];}
}
#pragma mark -UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YHomeItemRoundCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:YXHomeItemRound forIndexPath:indexPath];
    
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, collectionView.frame.size.height);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}














// 按钮事件
- (IBAction)btnEven:(UIButton *)sender {
    NSInteger index = sender.tag;

    NSArray *ctlAry = @[  [[NewMessage alloc] initWithNibName:@"NewMessage" bundle:nil],
                          [[FinancialReport alloc] initWithNibName:@"FinancialReport" bundle:nil],
                          [[RecordSlide alloc] init]
                          ];

    [self.navigationController pushViewController:[ctlAry objectAtIndex:index] animated:NO];

}













- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}













#pragma make 激光推送

- (void)jpush{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(serviceError:)
                          name:kJPFServiceErrorNotification
                        object:nil];

}

- (void)dealloc {
    [self unObserveAllNotifications];
}

- (void)unObserveAllNotifications {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter removeObserver:self
name:kJPFNetworkDidSetupNotification
                           object:nil];
    [defaultCenter removeObserver:self
name:kJPFNetworkDidCloseNotification
                           object:nil];
    [defaultCenter removeObserver:self
name:kJPFNetworkDidRegisterNotification
                           object:nil];
    [defaultCenter removeObserver:self
name:kJPFNetworkDidLoginNotification
                           object:nil];
    [defaultCenter removeObserver:self
name:kJPFNetworkDidReceiveMessageNotification
                           object:nil];
    [defaultCenter removeObserver:self
name:kJPFServiceErrorNotification
                           object:nil];
}


- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"已连接");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"未连接");
}

- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"%@", [notification userInfo]);
    NSLog(@"已注册");
}
#pragma make 获取激光id
- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");
    if ([JPUSHService registrationID]) {
        NSLog(@"get RegistrationID= %@", [JPUSHService registrationID]);
        NSDictionary *parameters = @{@"uid":@([YConfig getOwnID]) ,@"registrationID":[JPUSHService registrationID]};
        
        [ZL_NetworkHelper POST:GETREGISTRATIONID parameters:parameters success:^(id responseObject) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSString *res = IF_NULL_TO_STRING([dic objectForKey:@"res"]);
            NSString *msg = IF_NULL_TO_STRING([dic objectForKey:@"msg"]);

            if ([res isEqualToString:@"1"]) {
                // 保存激光注册id
                [YConfig saveRegistrationID:[JPUSHService registrationID]];
            }
            NSLog(@"msg=%@" ,msg);
        } failure:^(NSError *error) {
            NSLog(@"error.localizedDescription=%@" ,error.localizedDescription);
        }];
        
    }
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSLog(@"networkDidReceiveMessage");
}

- (void)serviceError:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *error = [userInfo valueForKey:@"error"];
    NSLog(@"%@", error);
}


- (void)addNotificationCount {
    _notificationCount++;
    [self reloadNotificationCountLabel];
}
- (void)addMessageCount {
    _messageCount++;
    [self reloadMessageCountLabel];
}

- (void)reloadMessageContentView {
}

- (void)reloadMessageCountLabel {
    NSLog(@"%@" ,[NSString stringWithFormat:@"%d", _messageCount]);
}

- (void)reloadNotificationCountLabel {
    NSLog(@"%@" ,[NSString stringWithFormat:@"%d", _notificationCount]);
}














@end
